<?php
    class VES_Vendors_Model_Account_Api_V2 extends  VES_Vendors_Model_Account_Api {
        protected     $result ="";
        
        
        protected     $defultCountry="CN";
        
        const WEBSITEID="1";
        public  function getRegionId($code){
        
            $dbr = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_read' );
        
            $sql = "select region_id from directory_country_region where country_id='{$this->defultCountry}' AND id_code='{$code}'";
            // $result = $dbr->fetchAll($sql);
            $result = $dbr->fetchOne($sql);      
            return $result;
        
        }
        /**
         *   vendors toRegister
         *   @param $info str
         *   @return   $result str
         * */
     
        
     public function toRegister($info) {
                try {     
                   //  new Varien_Simplexml_Config();
                  $data = json_decode($info,true);
                  if(empty($data['email'])){
                      $this->_fault("email is not empty!");
                  }
                  $model = $this->_returnVendor($data['email']);
                    
                    
                    $data['confirmation'] = $data['password'];
                    foreach($data as $key=>$value){
                        if($key == 'region_id'){
                            $data[$key]=$this->getRegionId($value);
                        } 
                        $model->setData($key,$value);
                    }
                    
                    $model->setregionID($data['region_id']);
                    $model->setCountryId($this->defultCountry);
                    if(!$model->getId()){
                        $model->setCreatedTime(now());
                    }
                   $model->setUpdateTime(now());   
                          if(is_array($erros=$model->validate())){   
                                    $this->result['error']='success';
                                    $this->result['info']=$erros;   
                                    return  json_encode($this->result) ;
                              exit;
                            };
                    $model->save();
                } catch (Mage_Core_Exception $e) {
                      $this->result['stauts']='error';
                      $this->result['info']=$e->getMessage(); 
                      Mage::log("商家注册账号接口错误数据:",1,"upload.log");
                      Mage::log($info,1,"upload.log");
                      return  json_encode($this->result) ;
                    exit;  
                }	     
				    /*Send new vendor account email 发送邮件*/
				    $vendorStoreId = Mage::app()->getWebsite($model->getWebsiteId())->getDefaultGroup()->getDefaultStoreId();
				        if(Mage::helper('vendors')->approvalRequired()){
				            $model->sendNewAccountEmail('registered','',$vendorStoreId);
				        }else{
				            $model->sendNewAccountEmail(
				                'registered',
				                '',
				                $vendorStoreId
				    				        );
				        }
				
                $this->result['status'] ="success";
                $this->result['info'] = $model->getId();
                 return   json_encode($this->result);
           }     
           
           public function toLogin($username,$password){
               /** @var $vendor VES_Vendors_Model_Vendor */
               $vendor = Mage::getModel('vendors/vendor');
               $session = Mage::getSingleton('vendors/session');
                
               $vendor->setWebsiteId(self::WEBSITEID);
               
               
               try {
               /*Check if login is email*/
               $validator = new Zend_Validate_EmailAddress();
               if($validator->isValid($username)) {
                   $vendor->loadByEmail($username,$vendor->getWebsiteId());
               }else{
                   $vendor->loadByVendorId($username,$vendor->getWebsiteId());
               }
               if (!$vendor->validatePassword($password)) {
                   $this->_fault('Invalid login or password.');
               }
               
               if ($vendor->getConfirmation() && $vendor->isConfirmationRequired()) {
                    
                   $this->_fault('Your vendor account is not confirmed.');
               }
               
               if ($vendor->getStatus() ==$vendor::STATUS_PENDING){
                   $this->_fault('Your vendor account is awaiting for approval.');
               }
               
               if ($vendor->getStatus() == $vendor::STATUS_DISABLED) {
               
                   $this->_fault('Your vendor account has been suppended');
                    
               }
               
               Mage::dispatchEvent('customer_customer_authenticated', array(
                   'model'    => $vendor,
                   'password' => $password,
               ));
               
               $this->result['status'] ="success";
               $this->result['info'] =$session->getVendor()->getData();
               } catch (Mage_Core_Exception $e) {
                   $this->result['status']='error';
                   $this->result['info']=$e->getMessage();
               } catch (Exception $e) {
                   $this->result['status']='error';
                   $this->result['info']=$e->getMessage();  
               }
               return  json_encode($this->result) ;
           }
    }